package com.cy.pj.sys.service.impl;

import com.cy.pj.common.bo.PageObject;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.entity.SysLog;
import com.cy.pj.sys.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LiuXu
 * @create 2020-07-11 15:37
 */
@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogDao sysLogDao;

    /**
     * @param username    条件查询参数
     * @param pageCurrent 当前页码值
     * @return
     * @throws ServiceException
     */
    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent) throws ServiceException {
        //验证pageCurrent合法性
        //不合法抛出异常
        if (pageCurrent == null || pageCurrent < 1) {
            throw new IllegalArgumentException("当前页码有误");
        }
        //基于条件查询总记录
        int rowCount = sysLogDao.getRowCount(username);
        //验证结果，结果为0就不再执行如下操作
        if (rowCount == 0) {
            throw new ServiceException("没有对应记录");
        }
        //基于条件查询当前页记录
        //定义pageSize
        int pageSize = 2;
        //计算startIndex
        int startIndex = (pageCurrent - 1) * pageSize;
        //执行当前数据查询操作
        List<SysLog> records = sysLogDao.findPageObjects(username, startIndex, pageSize);
        //分页信息及当前页记录进行封装
        //构建PageObject对象
        PageObject<SysLog> pageObject = new PageObject<>();
        //封装数据
        pageObject.setPageCount(pageCurrent);
        pageObject.setPageSize(pageSize);
        pageObject.setRowCount(rowCount);
        pageObject.setRecords(records);
        pageObject.setPageCount((rowCount - 1) / pageSize + 1);
        //返回封装结果
        return pageObject;
    }

    @Override
    public int deleteObjects(Integer... ids) {
        //判定参数合法性

        if (ids == null || ids.length == 0) {
            throw new IllegalArgumentException("请选择一个");
        }
        //执行删除
        int rows = 0;
        try {
            rows = sysLogDao.deleteObjects(ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("系统故障，正在恢复");
        }
        //验证结果
        if (rows == 0) {
            throw new ServiceException("记录不存在");
        }
        //返回结果
        return rows;

    }

    @Override
    public int saveObject(SysLog entity) {
        return sysLogDao.insertObject(entity);
    }
}
